package org.fujene.diskblock.repli;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.fujene.diskblock.DiskBlock;
import org.fujene.memoryblock.MemoryBlock;
import org.fujene.memoryblock.repli.ReplicateInvertIndexBlock;
import org.fujene.structure.Constants;
import org.fujene.structure.InvertIndexData;
import org.fujene.structure.LookupPointer;
import org.fujene.toolbox.ByteConverter;

public class ReplicateInvertIndexDiskBlock extends DiskBlock {
	public ReplicateInvertIndexDiskBlock(File fileDesc) throws Exception {
		super(fileDesc);
	}
	
	public ReplicateInvertIndexDiskBlock(int ID, File fileDesc, int defaultBodySize, int defaultOptionSize){
		super(ID, fileDesc, Constants.MEMORY_TYPE_INVINDEX, defaultBodySize, defaultOptionSize);
	}

	public ReplicateInvertIndexDiskBlock(ReplicateInvertIndexBlock memBlock, String dir) {
		super(memBlock, dir);
	}
	
	public InvertIndexData getInvertIndex(int ptr) throws IOException {
		if(ptr >= bodySize - (PTR + 4 + 4)) return null;
		
		FileInputStream stream = null;
		byte[] val = null;
		LookupPointer prevPtr = null;
		long diffID = -1;
		int termfreq = 0;
		try{
			stream = new FileInputStream(fileDesc);
			switch (version) {
			case Constants.FINALVER:
				stream.skip((4 * HEADERLEN) + (4 * optionSize) + ptr);
				val = new byte[PTR];
				stream.read(val);
				prevPtr = ByteConverter.getRelativePtr(val);
				if(prevPtr.equals(Constants.emptyPointer)){
					prevPtr = null;
				}else{
					prevPtr.block += this.getID();
				}
				
				val = new byte[4];
				stream.read(val);
				diffID = ByteConverter.byteToLong(val);
				
				val = new byte[DOCFREQ];
				stream.read(val);
				termfreq = ByteConverter.byteToInt(val);
				
				break;

			default:
				break;
			}
		}finally{
			if(stream != null)
				stream.close();
		}
		
		return new InvertIndexData(prevPtr, diffID, termfreq);
	}
	
	@Override
	public void readToMemory(MemoryBlock memBlock) {
		if(memBlock instanceof ReplicateInvertIndexBlock){
			try {
				memBlock.setOption(0, this.getOption(0));
				memBlock.setBody(this.getBody(0, this.bodySize), 0);
				memBlock.setBodyVacancy(this.bodyVacancy);
			} catch (Exception e) {
			}
		}
	}

	@Override
	public byte[] getData() {
		throw new NoSuchMethodError("Unimplemented method");
	}
}
